<template>
    <div>
        <!-- 一，面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 二，卡片视图区域 -->
        <el-card>
            <!-- 1，提示框 -->
            <el-alert title="消添加商品" type="info" center show-icon :closable="false">
            </el-alert>
            <!-- 2，步骤条 -->
            <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <!-- 3，tabs标签栏，左侧 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
                <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="beforeTabLeave"
                    @tab-click="tabClicked()">
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="addForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="价格" prop="goods_price">
                            <el-input v-model="addForm.goods_price"></el-input>
                        </el-form-item>
                        <el-form-item label="重量" prop="goods_weight">
                            <el-input v-model="addForm.goods_weight"></el-input>
                        </el-form-item>
                        <el-form-item label="数量" prop="goods_number">
                            <el-input v-model="addForm.goods_number"></el-input>
                        </el-form-item>
                        <el-form-item label="分类" prop="goods_cat">
                            <el-cascader expand-Trigger='hover' v-model="addForm.goods_cat" :options="catelist"
                                :props="cateProps" @change="handleChange"></el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <!-- 循环渲染 -->
                        <!-- <el-form-item :label="item.attr_name" v-for="(item, i) in manyTableData" :key="i"> -->
                        <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox :label="cb" v-for="(cb, i) in item.attr_vals" :key="i" border>
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                        <el-form-item :label="item.attr_name" v-for="(item) in onlyTableData" :key="item.attr_id">
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="3">
                        <el-upload :action="uploadURL" :on-preview="handlePreview" :on-remove="handleRemove"
                            list-type="picture" :headers="headerObj" :on-success="handleSuccess">
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <!-- 富文本编辑器 -->
                        <quill-editor v-model="addForm.goods_introduce"></quill-editor>
                        <!-- 添加按钮 -->
                        <el-button type="primary" class="addButton" @click="addGoods()">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>

        </el-card>
        <!-- 图片预览对话框 -->
        <el-dialog title="图片预览" :visible.sync="previewDialogVisible" width="50%">
            <img :src="preivewPath" alt="" class="previePic">
        </el-dialog>
    </div>
</template>
<!-- 
    添加商品组件页面 Add.vue
    1，面包屑，卡片。警示栏，步骤条，导入引用，修改，公共样式，默认激活定义data，activeIndex,tab栏左侧，
    2,步骤条和tabs栏关联联动：公用一个activeIndex，字符串，变数字就activeIndex-0，
    3，用form包裹着，加form-item，校验addFormRules，data定义好addForm，
    4，发送请求，商品分类，级联选择器，配置级联选择器，cateProps，选中项数组goods_cat，判断选择项是否长度为3 即选中的是三级选项，否则置空不给选。
    5,tabs栏切换之前要先判断是否一级选择3级商品，监听tabs切换，属性before-leave，:before-leave="beforeTabLeave注意不要加括号，注意'0',引号字符串，
    6，tabs栏切换，发送请求,动态属性，商品参数，填充数据，利用tabs栏点击事件tab-click，判断点击了谁，请求谁， 请求到的数据data定义 manyTableData 的 attr_vals，字符串变数组，来循环，用el多选框，el-checkbox，按需导入使用,这里有2次循环渲染，
    7，tabs栏切换，商品属性，发送请求,静态属性，data定义onlyTableData
    8,图片上传，按需导入使用，配置好:action="uploadURL" ，有个headers属性，请求头，需要带token，不然上传图片失败，:headers="headerObj",上传好还要处理下，把图片的临时途径保存到数据绑定表单中，有个方法on-success，:on-success="handleSuccess",方法:on-remove="handleRemove"，删除图片:on-preview="handlePreview"，预览图片， 图片预览对话框 ，img :src="preivewPath"
    9,安装依赖，富文本编辑，vue-quiil-editor，查看官方文档使用，安装后全局导入使用，SPA方式使用，加个添加按钮el-button，点击事件发送post请求，@click="addGoods()，校验，请求goods_cat参数要数组转成字符串，但注意渲染双向绑定时要求goods_cat是数组，不能直接数组.join（','）转成字符串，解决：addform做深拷贝，安装依赖lodash,本地组件导入，使用,import _ from 'lodash' 。
    10，另外发送post请求的参数form表单里面的attrs参数要处理，包括动静态参数，遍历forEach，push，赋值，接着发送请求post，跳转会goods页面。
    11，提交代码。
 -->
<script>
import _ from 'lodash'

export default {

    data() {
        return {
            // 步骤条激活
            activeIndex: '0',
            // tabs 栏,数据表单
            addForm: {
                goods_name: '',
                goods_price: '0',
                goods_weight: '0',
                goods_number: '0',
                goods_cat: [], //商品分类数组，级联选择器
                pics: [], // 上传图片,成功后获取图片临时地址
                goods_introduce: '',
                attrs: [],
            },
            // tabs 栏 ,校验
            addFormRules: {
                goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
                goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
                goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
                goods_number: [{ required: true, message: '请输入商品数据', trigger: 'blur' }],
                goods_cat: [{ required: true, message: '请输入商品分类', trigger: 'blur' }],
            },
            //获取商品分类
            catelist: [],
            // 级联选择器属性props配置对象
            cateProps: {
                value: 'cat_id',
                label: 'cat_name',
                children: 'children'
            },
            // tabs栏商品属性请求数据，动态，静态
            manyTableData: [],
            onlyTableData: [],
            // 上传图片后台地址
            uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
            // 上传图片,请求头带token
            headerObj: {
                Authorization: window.sessionStorage.getItem('token')
            },
            // 上传图片,获取图片临时地址
            preivewPath: '',
            previewDialogVisible: false,//显示隐藏

        };
    },

    computed: {
        // 获取三级选项id
        cateId() {
            if (this.addForm.goods_cat.length === 3) {
                return this.addForm.goods_cat[2]
            }
            return null
        },
    },

    created() {
        this.getCateList()
    },

    methods: {
        //获取商品分类
        async getCateList() {
            const { data: res } = await this.$http.get('categories')
            // console.log(res)
            if (res.meta.status !== 200) {
                return this.$message.error(res.meta.msg)
            }
            this.catelist = res.data
            this.$message.success(res.meta.msg)
        },

        //级联选择器，选中项变化，触发
        handleChange() {
            console.log(this.addForm.goods_cat)
            if (this.addForm.goods_cat.length !== 3) {
                this.addForm.goods_cat = []
            }
        },

        //切换tabs栏之前，先判断是否选择了三级商品
        beforeTabLeave(activeName, oldActiveName) {
            // console.log('即将离开：' + oldActiveName)
            // console.log('即将进入：' + activeName)
            // return false
            if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
                this.$message.error('请先选择商品分类')
                return false
            }
        },
        //tabs栏切换，判断切换了谁就发送请求填充
        async tabClicked() {
            // console.log(this.activeIndex)
            //访问动态参数面板,商品参数
            if (this.activeIndex === '1') {
                // console.log('访问动态参数面板')
                // this.$http.get(`categories/${this.addForm.goods_cat[2]}/attributes`)
                const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
                // console.log(res)
                // console.log(this.cateId)
                if (res.meta.status !== 200) {
                    return this.$message.error(res.meta.msg)
                }
                this.$message.success(res.meta.msg)
                res.data.forEach(item => {
                    item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
                })
                this.manyTableData = res.data
            } else if (this.activeIndex === '2') {
                //访问动态参数面板，商品属性
                const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
                console.log(res)
                // console.log(this.cateId)
                if (res.meta.status !== 200) {
                    return this.$message.error(res.meta.msg)
                }
                this.$message.success(res.meta.msg)
                this.onlyTableData = res.data

            }
        },

        // 图片上传图片预览，触发
        handlePreview(file) {
            // console.log(file)
            this.preivewPath = file.response.data.url
            this.previewDialogVisible = true
        },
        // 图片上传图片删除临时路径，触发
        handleRemove(file) {
            // console.log(file)
            const filePath = file.response.data.tmp_path
            const i = this.addForm.pics.findIndex(x =>
                x.pic === filePath   //查找对应索引值
            )
            this.addForm.pics.splice(i, 1)  //删除对应索引值
            // console.log(this.addForm)
        },

        // 上传图片,成功后获取图片临时路径
        handleSuccess(response) {
            // console.log(response)
            const picInfo = {
                pic: response.data.tmp_path
            }
            this.addForm.pics.push(picInfo)
            // console.log(this.addForm)

        },
        //添加按钮 ，校验，
        addGoods() {
            // console.log(this.addForm.goods_introduce)
            this.$refs.addFormRef.validate(async valid => {
                if (!valid) {
                    return this.$message.error('填写必要表单选项')
                }
                //深拷贝，表单，符合提交的数据格式
                const form = _.cloneDeep(this.addForm)
                form.goods_cat = form.goods_cat.join(',')
                // console.log(form)
                //处理动静态参数数组
                this.manyTableData.forEach(item => {
                    const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals.join(',') }
                    this.addForm.attrs.push(newInfo)
                })
                // 静态属性值本来就是字符串，所以不要加join
                this.onlyTableData.forEach(item => {
                    const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
                    this.addForm.attrs.push(newInfo)
                })
                form.attrs = this.addForm.attrs
                console.log(form)
                //发送请求post
                const { data: res } = await this.$http.post('goods', form)
                console.log(res)
                if (res.meta.status !== 201) {
                    return this.$message.error(res.meta.msg)
                }
                this.$message.success(res.meta.msg)
                this.$router.push('/goods')

            })
        }
    },
};
</script>

<style lang="less" scoped >
.el-checkbox {
    margin: 5px;

}

.previePic {
    width: 100%;

}

.addButton {
    margin-top: 30px
}
</style>